package nl.vu.few.ibivu.biomodels.client.presenter;

import java.util.EmptyStackException;
import java.util.Stack;

import nl.vu.few.ibivu.biomodels.client.event.MessageBroadcastEvent;
import nl.vu.few.ibivu.biomodels.client.event.MessageBroadcastEventHandler;
import nl.vu.few.ibivu.biomodels.client.event.MessageBroadcastType;
import nl.vu.few.ibivu.biomodels.client.ui.MessageViewImpl;
import nl.vu.few.ibivu.biomodels.client.ui.view.MessageView;
import nl.vu.few.ibivu.biomodels.client.ui.view.MessageView.Presenter;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

public class MessagePresenter extends AbstractPresenter implements Presenter, MessageBroadcastEventHandler {
	private Stack<MessageView> messageStack;
	
	@Inject
	public MessagePresenter(EventBus eventBus, PlaceController placeController) {
		super(eventBus, placeController);
		messageStack = new Stack<MessageView>();
		MessageBroadcastEvent.register(eventBus, this);
	}

	@Override
	public void addMessage(MessageBroadcastType type, String message) {
		messageStack.push(new MessageViewImpl(this, type, message).display());
	}
	
	@Override
	public void removeMessage(MessageView message) {
		messageStack.remove(message);
	}

	@Override
	public void addMessage(MessageView message) {
		messageStack.push(message);
	}

	@Override
	public Widget getView() {
		MessageView last;
		try {
			last = messageStack.peek();
		}
		catch(EmptyStackException e) {
			return null;
		}
		return last.asWidget();
	}

	@Override
	public void onMessageReceived(MessageBroadcastEvent messageBroadcastEvent) {
		addMessage(messageBroadcastEvent.getMessageType(), messageBroadcastEvent.getMessage());
	}
}
